import 'package:get/get.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/components/custom_select_function.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/application/department_user_entity.dart';
import 'package:safetymonitor/app/data/entities/application/preventive_rectification_create_entity.dart';
import 'package:safetymonitor/modules/home/home_page/home_page_control.dart';
import 'package:safetymonitor/router/app_pages.dart';

/// 新增隐患（只需要判断是否是100 就可看可以了  分公司和整改人是一个级别）
class AddHazardController extends GetxController {
  /// 请求实体
  PreventiveRectificationCreateEntity preventiveRectificationCreateEntity = PreventiveRectificationCreateEntity();

  /// 公司列表（不含总公司）
  List<CorporationNameEntity> nameListNO = [];

  // 选中的公司（center）
  CorporationNameEntity? _selectIdCenter;

  // 选中的责任部门
  List<CorporationNameEntity> selectIdDeptList = [];

  // 显示责任部门的名字
  String get selectIdDeptName {
    StringBuffer sb = StringBuffer();
    for (int i = 0; i < selectIdDeptList.length; i++) {
      sb.write(selectIdDeptList[i].getShowName());
      if (i != selectIdDeptList.length - 1) {
        sb.write(',');
      }
    }
    return sb.toString();
  }

  // 选中的责任人
  List<DepartmentUserEntity> selectIdPersonList = [];

  // 显示责任人的名字
  String get selectIdPersonName {
    StringBuffer sb = StringBuffer();
    for (int i = 0; i < selectIdPersonList.length; i++) {
      sb.write(selectIdPersonList[i].getShowName());
      if (i != selectIdPersonList.length - 1) {
        sb.write(',');
      }
    }
    return sb.toString();
  }


  // 选中的整改部门
  List<CorporationNameEntity> selectIdRectificationList = [];

  // 显示整改部门的名字
  String get selectIdRectificationName {
    StringBuffer sb = StringBuffer();
    for (int i = 0; i < selectIdRectificationList.length; i++) {
      sb.write(selectIdRectificationList[i].getShowName());
      if (i != selectIdRectificationList.length - 1) {
        sb.write(',');
      }
    }
    return sb.toString();
  }

  // 选中的整改人
  List<DepartmentUserEntity> selectIdRectificationPersonList = [];

  // 显示整改人的名字
  String get selectIdRectificationPersonName {
    StringBuffer sb = StringBuffer();
    for (int i = 0; i < selectIdRectificationPersonList.length; i++) {
      sb.write(selectIdRectificationPersonList[i].getShowName());
      if (i != selectIdRectificationPersonList.length - 1) {
        sb.write(',');
      }
    }
    return sb.toString();
  }



  /// 图片
  List<String> dangerImages = [];

  /// 视频
  List<String> dangerVideo = [];

  DateTime dateTime = DateTime.now();

  @override
  void onInit() {
    super.onInit();
    if (UserManager.getUserCompanyId() == 100) {
      preventiveRectificationCreateEntity.isHead = true;
    }
    //浅拷贝
    nameListNO = List.from(Get.find<HomePageControl>().nameList);
    for (int i = 0; i < nameListNO.length; i++) {
      if (nameListNO[i].id == 100) {
        nameListNO.remove(nameListNO[i]);
      }
    }
  }

  /// 确定提交
  Future<void> confirm() async {
    if (preventiveRectificationCreateEntity.preventiveName.trim().isEmpty) {
      AppToast.showError('请输入隐患名称');
      return;
    }
    if (preventiveRectificationCreateEntity.companyName.trim().isEmpty&& preventiveRectificationCreateEntity.isHead) {
      AppToast.showError('请选择责任单位');
      return;
    }
    if(preventiveRectificationCreateEntity.isHead) {
      if(selectIdDeptList.isEmpty) {
        AppToast.showError('请选择责任部门');
        return;
      }
      if(selectIdPersonList.isEmpty) {
        AppToast.showError('请选择责任人');
        return;
      }
      preventiveRectificationCreateEntity.deptIds = selectIdDeptList.map((e) => e.id).join(',');
      preventiveRectificationCreateEntity.deptNames = selectIdDeptList.map((e) => e.getShowName()).join(',');
      preventiveRectificationCreateEntity.responsibleUsers = selectIdPersonList.map((e) => e.id).join(',');
      preventiveRectificationCreateEntity.responsibleUserNames = selectIdPersonList.map((e) => e.getShowName()).join(',');
    } else {
      if(selectIdRectificationList.isEmpty) {
        AppToast.showError('请选择整改部门');
        return;
      }
      if(selectIdRectificationPersonList.isEmpty) {
        AppToast.showError('请选择整改人');
        return;
      }
      preventiveRectificationCreateEntity.rectificationDeptIds = selectIdRectificationList.map((e) => e.id).join(',');
      preventiveRectificationCreateEntity.rectificationDeptNames = selectIdRectificationList.map((e) => e.getShowName()).join(',');
      preventiveRectificationCreateEntity.rectificationUserIds = selectIdRectificationPersonList.map((e) => e.id).join(',');
      preventiveRectificationCreateEntity.rectificationUserNames = selectIdRectificationPersonList.map((e) => e.getShowName()).join(',');
    }

    if ( preventiveRectificationCreateEntity.findTime ==0) {
      AppToast.showError('请选择发现时间');
      return;
    }  if (preventiveRectificationCreateEntity.rectificationDeadline==0) {
      AppToast.showError('请选择整改期限');
      return;
    }
    if (preventiveRectificationCreateEntity.problemDesc.trim().isEmpty) {
      AppToast.showError('请输入问题描述');
      return;
    }
    //当前账号公司id
    preventiveRectificationCreateEntity.companyId=UserManager.getUserCompanyId()??0;
    print('${preventiveRectificationCreateEntity.toJson()}');
    // 调用接口 todo
    final res = await HttpUtil().generatePostRequest(Interface.preventiveRectificationCreate,
        data: preventiveRectificationCreateEntity.toJson(),
    ).execute(isShowLoading: true);

    res.onSuccess((result) {
      Get.back();
      AppToast.showSuccess('提交成功');
    });
  }

  /// 发现时间选择
  void showDatePicker() {
    CustomSelectFunction.selectDateTime(
        onCallBack: (String value) {
          preventiveRectificationCreateEntity.findTime = int.parse(value);
          update();
        },
        isTimeStamp: true,
      lastDateY: dateTime.year,
      lastDateM: dateTime.month,
      lastDateD: dateTime.day,
      lastDateH: dateTime.hour,
      lastDateMinute: dateTime.minute,
      lastDateSecond: dateTime.second,
    );
  }

  /// 整改期限选择
  void showDatePicker2() {
    CustomSelectFunction.selectDateTime(
      onCallBack: (String value) {
        preventiveRectificationCreateEntity.rectificationDeadline =
            int.parse(value);
        update();
      },
      isTimeStamp: true,
      firstDateY: dateTime.year,
      firstDateM: dateTime.month,
      firstDateD: dateTime.day,
      firstDateH: dateTime.hour,
      firstDateMinute: dateTime.minute,
      firstDateSecond: dateTime.second,
    );
  }

  /// 责任单位
  void selectCurrentDept() {
    // Get.to(()=>CommonSelectionPage<DeptRespEntity>(title: '责任单位', enableLoad: false), arguments: {
    //   'interfaceUrl': Interface.getCurrentDept,
    // })?.then((value) {
    //   //如果不为空则设置信息
    //   if (value != null) {
    //     final DeptRespEntity  deptRespEntity = value[0] as DeptRespEntity;
    //     preventiveRectificationCreateEntity.companyName = deptRespEntity.name;
    //     preventiveRectificationCreateEntity.companyId = deptRespEntity.id;
    //     update();
    //   }
    // });
    CustomEquipmentBottomSheet<CorporationNameEntity>(
      dataList: nameListNO,
      checkedList: _selectIdCenter != null ? [_selectIdCenter!] : [],
      onConfirm: (value) {
        if (value.isNotEmpty) {
          _selectIdCenter = value[0];
          preventiveRectificationCreateEntity.companyName =
              value[0].getShowName();
          preventiveRectificationCreateEntity.companyId = value[0].id ?? 0;
          update();
        }
      },
      title: '选择公司',
      isMultiple: false,
    ).showBottomSheetDialog();
  }

  /// 选择完责任单位后,选择责任部门
  void selectCurrentDept2() async {
    if(_selectIdCenter == null) {
      AppToast.showError('请选择责任单位');
      return;
    } else {
      final res = await HttpUtil().generateGetRequest<List<CorporationNameEntity>>(Interface.mainBaseUrl + '/admin-api/system/dept/getByParent',queryParameters: {
        'parentId' : _selectIdCenter?.id,
      }).execute();
      if(res.isSucceed) {
        final List<CorporationNameEntity> list = res.data!;
        list.insert(0, CorporationNameEntity(
          name: _selectIdCenter?.name,
          id: _selectIdCenter?.id,
          createTime: 0,
          email: '',
          flag: 0,
          leaderUserId: 0,
          parentId: 0,
          sort: 0,
          status: 0,
          phone: '',
        ));
        CustomEquipmentBottomSheet<CorporationNameEntity>(
          dataList: list,
          checkedList: selectIdDeptList ?? [],
          onConfirm: (value) {
            if (value.isNotEmpty) {
              selectIdDeptList = value;
              update();
            }
          },
          title: '选择责任单位',
          isMultiple: true,
        ).showBottomSheetDialog();
      }

    }
  }

  /// 选完责任部门后,根据选择的部门去拿责任人
  void selectCurrentDept3() async {
    if(selectIdDeptList.isEmpty) {
      AppToast.showError('请选择责任部门');
      return;
    } else {
      // 获取 selectIdDeptList 的所有id,用,号拼起来
      final String deptId = selectIdDeptList.map((e) => e.id).join(',');
      final res = await HttpUtil().generateGetRequest<List<DepartmentUserEntity>>('${Interface.mainBaseUrl}/admin-api/system/user/getListByDeptIds',queryParameters: {
        'deptId' : deptId,
      }).execute();
      if(res.isSucceed) {
        final List<DepartmentUserEntity> list = res.data!;
        CustomEquipmentBottomSheet<DepartmentUserEntity>(
          dataList: list,
          checkedList: selectIdPersonList ?? [],
          onConfirm: (value) {
            if (value.isNotEmpty) {
              selectIdPersonList = value;
              update();
            }
          },
          title: '选择责任人',
          isMultiple: true,
        ).showBottomSheetDialog();
      }

    }
  }

  /// 选择整改部门
  void selectRectificationDept() async {
    final res = await HttpUtil().generateGetRequest<List<CorporationNameEntity>>('${Interface.mainBaseUrl}/admin-api/system/dept/getByParent',queryParameters: {
      'parentId' : UserManager.getUser()?.dept.parentId,
    }).execute();
    if(res.isSucceed) {
      final List<CorporationNameEntity> list = res.data!;
      CustomEquipmentBottomSheet<CorporationNameEntity>(
        dataList: list,
        checkedList: selectIdRectificationList ?? [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            selectIdRectificationList = value;
            update();
          }
        },
        title: '选择整改部门',
        isMultiple: true,
      ).showBottomSheetDialog();
    }
  }

  /// 选择整改人
  void selectRectificationPerson() async {
    if(selectIdRectificationList.isEmpty) {
      AppToast.showError('请选择整改部门');
      return;
    } else {
      // 获取 selectIdDeptList 的所有id,用,号拼起来
      final String deptId = selectIdRectificationList.map((e) => e.id).join(',');
      final res = await HttpUtil().generateGetRequest<List<DepartmentUserEntity>>('${Interface.mainBaseUrl}/admin-api/system/user/getListByDeptIds',queryParameters: {
        'deptId' : deptId,
      }).execute();
      if(res.isSucceed) {
        final List<DepartmentUserEntity> list = res.data!;
        CustomEquipmentBottomSheet<DepartmentUserEntity>(
          dataList: list,
          checkedList: selectIdRectificationPersonList ?? [],
          onConfirm: (value) {
            if (value.isNotEmpty) {
              selectIdRectificationPersonList = value;
              update();
            }
          },
          title: '选择整改人',
          isMultiple: true,
        ).showBottomSheetDialog();
      }

    }
  }


  /// 选择隐患整改人
  /// 已弃用
  void selectReportingPersonnel() {
    //第一种方式
    Get.toNamed(Routes.personnelDepartmentTreePage, arguments: {
      'title':UserManager.getUserCompanyName(),
      'isRadio': false,
    })?.then((value) {
      //如果不为空则设置人员信息
      if (value != null) {
        final List<DepartmentUserEntity> personList = value as List<DepartmentUserEntity>;
              preventiveRectificationCreateEntity.rectificationPersonId = int.parse(personList[0].id??'0');
              preventiveRectificationCreateEntity.rectificationPersonIdName = personList[0].getShowName();
              update();
      }
    });
  //第二种方式  主公司显示所有部门
  //   Get.toNamed(Routes.selectPeople)?.then((value) {
  //     if (value != null && value is UserRespEntity) {
  //       final UserRespEntity confirmBy = value;
  //       preventiveRectificationCreateEntity.rectificationPersonId = confirmBy.id;
  //       preventiveRectificationCreateEntity.rectificationPersonIdName = confirmBy.getShowName();
  //       update();
  //     }
  //   });
  }
}
